package com.mass.core.sys.dict.controller;


import com.mass.core.sys.dict.model.SysDictVal;
import com.mass.core.sys.dict.service.SysDictValService;
import com.mass.core.sys.file.model.FileInfoTemp;
import com.mass.core.sys.file.service.FileUploadService;
import com.mass.core.utils.AjaxResponse;
import com.mass.core.utils.ExcelUtil;
import com.mass.core.utils.RandomChar;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


/**
 * annotation:SysDictVal 控制层
 * created by pannan on 2017/08/25
 */
@RestController
@RequestMapping(value = "/sys/dictVal")
public class SysDictValController {

    private final static Logger LOGGER = LoggerFactory.getLogger(SysDictTypeController.class);

    @Autowired
    private SysDictValService sysDictValService;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 获取详情
     *
     * @param id 文件id
     * @return
     */
    @RequestMapping(value = "/getEntityById", method = RequestMethod.GET)
    public AjaxResponse getEntityById(@RequestParam("id") Long id) {
        try {
            SysDictVal sysDictVal = this.sysDictValService.getEntityById(id);
            return AjaxResponse.success("ok", sysDictVal);
        } catch (Exception e) {
            LOGGER.error("select SysDictVal error!", e);
            return AjaxResponse.error("error");
        }
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public AjaxResponse uploadFile(MultipartHttpServletRequest request,
                                   HttpServletResponse response, String typeCode) {
        List<FileInfoTemp> list = new ArrayList<FileInfoTemp>();
        if (!ObjectUtils.isEmpty(typeCode)) {
            list = this.fileUploadService.uploadFile(request, null, false);
        } else {
            return AjaxResponse.error("请选择字典类型！");
        }
        if (list.size() > 0) {
            FileInfoTemp fileInfoTemp = list.get(0);
            String filePath = fileInfoTemp.getFilePath();
            LinkedList[] result = new LinkedList[10];
            FileInputStream inStream = null;
            try {
                File file = new File(filePath);
                inStream = new FileInputStream(file);
                Workbook workBook = WorkbookFactory.create(inStream);
                Sheet sheet = workBook.getSheetAt(0);
                int rowNum = sheet.getLastRowNum() + 1;
                result = new LinkedList[rowNum];
                for (int i = 0; i < rowNum; i++) {
                    Row row = sheet.getRow(i);
                    //每有新的一行，创建一个新的LinkedList对象
                    result[i] = new LinkedList();
                    for (int j = 0; j < 1; j++) {
                        Cell cell = row.getCell(j);
                        //获取单元格的值
                        String str = ExcelUtil.getCellValue(cell);
                        //将得到的值放入链表中
                        result[i].add(str);
                    }
                }
                //System.out.println(result);
                for (int i = 1; i < result.length; i++) {
                    System.out.println("\t" + result[i].get(0) + "\t");
                    String valName = "";
                    if (!ObjectUtils.isEmpty(result[i].get(0))) {
                        valName = result[i].get(0).toString().trim();
                    }
                    if (!ObjectUtils.isEmpty(valName)) {
                        String valCode = RandomChar.getRandom(6, RandomChar.TYPE.LETTER_CAPITAL);
                        while (!sysDictValService.checkValCodeIsExist(valCode)) {
                            valCode = RandomChar.getRandom(6, RandomChar.TYPE.LETTER_CAPITAL);
                        }
                        SysDictVal sysDictVal = new SysDictVal();
                        sysDictVal.setValName(valName);
                        sysDictVal.setValCode(valCode);
                        sysDictVal.setSortIndex(i);
                        sysDictVal.setTypeCode(typeCode);
                        sysDictValService.addEntity(sysDictVal);
                    }
                }
                if (result.length == 1) {
                    return AjaxResponse.error("Excel 无数据！");
                }
                return AjaxResponse.success("操作成功！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return AjaxResponse.error("上传失败！");
    }

    /*
     * 添加数据词典
     * @param sysDictVal
     * */
    @RequestMapping(value = "/addEntity", method = RequestMethod.POST)
    public AjaxResponse addEntity(SysDictVal sysDictVal) {
        try {
            this.sysDictValService.addEntity(sysDictVal);
            return null == sysDictVal ? AjaxResponse.error("error", sysDictVal) : AjaxResponse.success("ok", sysDictVal);
        } catch (Exception e) {
            LOGGER.error("add SysDictVal error!", e);
            return AjaxResponse.error("error", sysDictVal);
        }

    }

    /*
     * 修改数据词典
     * @param sysDictVal
     * @param id
     */
    @RequestMapping(value = "/editEntity", method = RequestMethod.POST)
    public AjaxResponse editEntity(SysDictVal sysDictVal) {
        try {
            return this.sysDictValService.editEntity(sysDictVal) ? AjaxResponse.success("ok") : AjaxResponse.error("error", sysDictVal);
        } catch (Exception e) {
            LOGGER.error("edit SysDictVal error!", e);
            return AjaxResponse.error("error", sysDictVal);
        }

    }

    /*
     * 删除数据词典
     * @param id
     */
    @RequestMapping(value = "/deleteEntity", method = RequestMethod.GET)
    public AjaxResponse deleteEntity(@RequestParam("id") Long id) {
        try {
            return this.sysDictValService.deleteEntity(id) ? AjaxResponse.success("ok") : AjaxResponse.error("error", id);
        } catch (Exception e) {
            LOGGER.error("delete SysDictVal error!", e);
            return AjaxResponse.error("error");
        }
    }

    /**
     * 根据词典类型 编码查询
     *
     * @param typeCode 编码
     **/
    @RequestMapping(value = "/getByTypeCode", method = RequestMethod.GET)
    public AjaxResponse getByTypeCodeAll(String typeCode,String valName,String valCode, Integer enabled, String strs, String description) {
        try {
            List<String> strList = new ArrayList<String>();
            if (!ObjectUtils.isEmpty(strs)) {
                strList = Arrays.asList(strs.split(","));
            }
            List<SysDictVal> sysDictValList = this.sysDictValService.getByTypeCode(typeCode,valName,valCode, enabled, strList, description);
            return AjaxResponse.success("ok", sysDictValList);
        } catch (Exception e) {
            LOGGER.error("SysDictVal getByTypeCode error!", e);
            return null;
        }
    }


    /**
     * 验证编码唯一
     *
     * @param valCode 编码
     */
    @RequestMapping(value = "/checkValCodeIsExist", method = RequestMethod.POST)
    public boolean checkValCodeIsExist(@RequestParam("valCode") String valCode) {

        return this.sysDictValService.checkValCodeIsExist(valCode);

    }

    /**
     * 根据valCode获取名称
     *
     * @param valCode 编码
     **/
    @RequestMapping(value = "/getValNameByValCode", method = RequestMethod.GET)
    public AjaxResponse getValNameByValCode(@RequestParam("valCode") String valCode) {
        try {
            SysDictVal sysDictVal = this.sysDictValService.getValNameByValCode(valCode);
            return AjaxResponse.success("ok", sysDictVal);
        } catch (Exception e) {
            LOGGER.error("SysDictVal getValNameByValCode error!", e);
            return AjaxResponse.error("error");
        }
    }
}
